package com.teach.sys.api;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.teach.AuthUser;
import com.teach.R;
import com.teach.annotation.CheckLogin;
import com.teach.sys.entity.User;
import com.teach.sys.service.UserService;
import com.teach.util.JwtUtil;


/**  <pre>
 * Copyright 2022 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 * @author J.L.Zhou
 * @since 2022年11月08日 10:15:22
 * @version 1.0
 */
@RestController
@RequestMapping("/sys/auth")
@Validated
public class AuthApi {

  @Autowired
	private UserService userService;

  @Autowired
  private JwtUtil jwtUtil;


  @PostMapping("login")
  public R<?> login(
          @NotBlank(message = "手机号码不能为空")
          @Pattern(regexp = "^1\\d{10}$",message = "手机号码格式不正确")
          String userTel,
          @NotEmpty(message = "密码不能为空") //PS:@NotBlank和@NotEmpty有什么区别?
          String userPwd
  ){
    AuthUser user = userService.login(userTel, userPwd);
    return R.ok().setData(jwtUtil.create(user));
  }
  

  /**
   * 获取新的token
   * @return
   */
  @GetMapping("reload-token")
  @CheckLogin
  public R<?> reloadToken(){
    AuthUser user = AuthUser.get();
    return R.ok().setData(jwtUtil.create(user));
  }

  /**
   * 获取登录用户的信息
   * @return
   */
  @GetMapping("get")
  @CheckLogin
  public User getUser() {
      return userService.getById(AuthUser.get().getUserId());
  }
  
  
}
